package drone;

/**
 *
 * @author Robert Verginien Nickel
 */
import java.util.ArrayList;
import java.util.Collections;

public class DataBaseSpaces {
	
    private static DataBaseSpaces dbs = null;
    private static ArrayList<Space> allSpaces;
    /**
     * Constructor is private
     */
    private DataBaseSpaces(){}

    /**
     * Singleton-Pattern is implemented
     * You need to use this instead of a constructor
     * @return an object of DataBaseSpaces
     */
    public static DataBaseSpaces getInstance(){            
            if(dbs == null){ 
                dbs = new DataBaseSpaces();
                allSpaces = DBSReader.textToData();
                Collections.sort(allSpaces);
                return dbs;
            }
            return dbs;
    }

    /**
     * Adds a new space in the database and sorts it
     * @param space
     */
    public void addSpace(Space space){
            allSpaces.add(space);
            Collections.sort(allSpaces);
    }

    /**
     * Prints the x-, y-Coordinate and the distance
     * Print must always be sorted
     */
    @Override
    public String toString() {
            for (int i = 1 ; i<allSpaces.size()+1 ; i++){
                    System.out.println(i+". Entry has Coords at x: "+allSpaces.get(i-1).getCoordinates().getxPos()+
                                    " and y: "+allSpaces.get(i-1).getCoordinates().getzPos()+" and is "+
                                    allSpaces.get(i-1).getDistanceToStart()+" meters away from the start");
            }
            return "The amount is "+allSpaces.size()+" parking Spaces.";
    }

    public ArrayList<Space> getAllSpaces(){
        return allSpaces;
    }

    /**
     * Return the closest Space to the Coordinates
     * The Car needs this for leaving, to set the Space empty
     * @param coords
     * @return 
     */
    public Space findClosestSpace(Coordinates coords){
        Space toReturn = allSpaces.get(0);
        double bestLength = 1000;
        for(int i = 0; i < allSpaces.size(); i++){     
            double a = Math.abs(allSpaces.get(i).getCoordinates().getxPos() - coords.getxPos());
            double b = Math.abs(allSpaces.get(i).getCoordinates().getzPos() - coords.getzPos());
            if(Math.sqrt(Math.pow(a, 2)+Math.pow(b, 2)) < bestLength){
                bestLength = Math.sqrt(Math.pow(a, 2)+Math.pow(b, 2));
                toReturn = allSpaces.get(i);
            }
        }
        return toReturn;
    }
}